package org.glxy.shop.controller;

import org.glxy.shop.entity.Product;
import org.glxy.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    // GET /api/products - 查询商品列表（支持标签筛选）
    @GetMapping
    public ResponseEntity<Page<Product>> getProducts(
            @RequestParam(required = false) List<String> tags,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Page<Product> products = productService.getProducts(tags, page, size);
        return ResponseEntity.ok(products);
    }

    // POST /api/products - 创建商品
    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        // 验证标签数量
        if (product.getTags() != null && product.getTags().size() > 8) {
            return ResponseEntity.badRequest().build();
        }
        
        Product createdProduct = productService.createProduct(product);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdProduct);
    }

    // PUT /api/products/{id} - 更新商品
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(
            @PathVariable String id,
            @RequestBody Product product) {
        // 验证标签数量
        if (product.getTags() != null && product.getTags().size() > 8) {
            return ResponseEntity.badRequest().build();
        }
        
        Product updatedProduct = productService.updateProduct(id, product);
        if (updatedProduct == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(updatedProduct);
    }

    // GET /api/products/{id} - 获取商品详情
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable String id) {
        Product product = productService.getProductById(id);
        if (product == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(product);
    }
}